package targaman.moltenwow.autovoter.gui;

import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import targaman.moltenwow.autovoter.Logger.MoltenLogger;
import targaman.moltenwow.autovoter.controllers.ConfigurationImpl;
import targaman.moltenwow.autovoter.lang.Constants;

import java.io.IOException;

public class Main extends Application {

    public static Scene scene;


    @Override public void start(Stage primaryStage) throws IOException {


        FXMLLoader fxmlLoader=new FXMLLoader(ClassLoader.getSystemResource("StartScreen.fxml"));
        ApplicationContext context = new ClassPathXmlApplicationContext(ClassLoader.getSystemResource("connectivity.xml").toString());
        Controller foundConnectivityController = (Controller)context.getBean(Constants.GUI_CONTROLLER);
        fxmlLoader.setController(foundConnectivityController);
        Pane root=(Pane)fxmlLoader.load();



        scene=new Scene(root,root.getPrefWidth(),root.getPrefHeight());
        primaryStage.setScene(scene);
        primaryStage.setTitle("Molten AutoVoter");
        primaryStage.show();
        ((Controller)fxmlLoader.getController()).loadConfiguration();
        ((Controller)fxmlLoader.getController()).updateMenuGui();
        Task task = new Task<Void>() {
            @Override
            public Void call() throws Exception {
//                ((Controller)fxmlLoader.getController()).login();
                while(true) {
                    String autoLogin = ((Controller) fxmlLoader.getController()).getConfigurationService().getValueFromKeyInConfiguration(ConfigurationImpl.SET_AUTO_LOGIN);
                    if (autoLogin != null && autoLogin.contains("true")) {
                        ((Controller) fxmlLoader.getController()).login();
                    }


                    Thread.sleep(1000 * 60 * 60);
                    MoltenLogger.Log("--MoltenWoW Hourly Check--");
                }

            }
        };
        Thread thx = new Thread(task);
        thx.setDaemon(true);
        new Thread(thx).start();
        //Add Timer for auto vote (every hour)
        //Add to windows startup
        //Start Minimised
        //Track Vote Points

    }


    public static void main(String[] args) {
        launch(args);
    }
}
